﻿namespace OnHook.Common.Collections
{
    /// <summary>
    /// 固定大小的容器（超过容器大小，最先进入的会被顶替），采用List实现
    /// </summary>
    public class FixedSizeContainner<T>(int count) : List<T>()
    {
        private readonly int _limitCount = count;

        public int LimitCount { get; private set; }

        /// <summary>
        /// 添加元素
        /// </summary>
        /// <param name="item">添加的元素</param>
        /// <returns>被移除的元素</returns>
        public new T? Add(T item)
        {
            // return AddRange(new List<T>() { item }).FirstOrDefault();
            T? obj = default;
            base.Add(item);
            if (this.Count > _limitCount)
            {
                obj = this[0];
                Remove(obj);
            }
            return obj;
        }

        /// <summary>
        /// 添加列表
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public new IEnumerable<T> AddRange(IEnumerable<T> list)
        {
            var outList = new List<T>();
            int outCount = this.Count + list.Count() - this._limitCount;
            try
            {
                base.AddRange(list);
            }
            catch (Exception)
            {

            }
            if (outCount > 0)
            {
                for (int i = 0; i < outCount; i++)
                {
                    var item = this[0];
                    if (Remove(item))
                    {
                        outList.Add(item);
                    }
                }
            }

            return outList;
        }

    }
}
